import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { CircleEntity } from '../entity/circle';
import { Context } from '@midwayjs/koa';
import { DictInfoService } from '../../dict/service/info';
import { FollowsEntity } from '../entity/follows';
import { UserEntity } from '../entity/user';

/**
 * 圈子
 */
@Provide()
export class CircleService extends BaseService {
    @Inject()
    ctx: Context;

    @Inject()
    dictInfoService: DictInfoService;

    @InjectEntityModel(CircleEntity)
    circleEntity: Repository<CircleEntity>;

    @InjectEntityModel(FollowsEntity)
    followsEntity: Repository<FollowsEntity>;

    @InjectEntityModel(UserEntity)
    userEntity: Repository<UserEntity>;

    /**
     * 圈子数据
     */
    async getCircleData() {
        try {
            const userCount = await this.userEntity.count({ where: { status: 1 } });
            const userList = await this.userEntity.find({
                where: {
                    status: 1
                },
                order: {
                    createTime: 'DESC'
                },
                take: 4
            });
            const data = {
                userCount: userCount,
                avatar: userList.map(item => { return  item.avatar  })
            }
            return {
                success: true,
                message: '查询成功',
                data: data
            }
        } catch (error) {
            throw new CoolCommException('查询失败');
        }
    }

    /**
     * 精选圈子
     */
    async getFineCircle() {
        try {
            const sql = `
                SELECT
                    a.id, a.name, a.description, a.cover, a.openid, a.status, a.createTime,
                    IFNULL(b.followCount, 0) followCount
                FROM
                    app_circle a
                LEFT JOIN (
                    SELECT
                        followId,
                        COUNT( * ) followCount
                    FROM
                        app_follows
                    WHERE
                        type = 0
                    GROUP BY
                        followId
                ) b ON a.id = b.followId
                WHERE
                    a.status = 1
                ORDER BY
                    b.followCount DESC
                LIMIT 100
            `;
            const list = await this.circleEntity.query(sql);
            const data = JSON.parse(JSON.stringify(list));
            data.forEach(item => { item.cover = item.cover.split(','), item.followCount = `${item.followCount}人关注` });
            return {
                success: true,
                message: '查询成功',
                data: data
            }
        } catch (error) {
            throw new CoolCommException('查询失败');
        }
    }

    /**
     * 我的圈子
     */
    async getMyCircle() {
        try {
            /**
               @Entity('app_circle')
               export class CircleEntity extends BaseEntity {
               @Column({ comment: '圈子名称', type: 'varchar', length: 50 })
                   name: string;
                @Column({ comment: '圈子描述', type: 'varchar', length: 255 })
                description: string;

                @Column({ comment: '圈子封面', type: 'varchar', length: 500 })
                cover: string;

                @Column({ comment: '圈子分类', type: 'varchar', length: 50 })
                categoryIds: string;

                @Column({ comment: '创建者', type: 'varchar', length: 50 })
                openid: string;

                @Column({ comment: '状态 0:禁用 1:启用', default: 0, type: 'tinyint' })
                status: number;
            }

            @Entity('app_follows')
            export class FollowsEntity extends BaseEntity {
                @Column({ comment: '关注类型 0:圈子 1:用户', type: 'tinyint' })
                type: number;
                
                @Column({ comment: '用户ID', type: 'int' })
                userId: number;
                
                @Column({ comment: '关注ID', type: 'int' })
                followId: number;
            }
             */

            /**
             * 1.查询 app_follows  type = 0，userId = this.ctx.user.userId 的所有 followId
             * 2.根据 followId 查询 app_circle id, name, description, cover, openid, status
             */
            const sql = `
                SELECT
                    a.id, a.name, a.description, a.cover, a.openid, a.status,
                    IFNULL(b.followCount, 0) followCount
                FROM
                    app_circle a
                LEFT JOIN (
                    SELECT
                        followId,
                        COUNT( * ) followCount
                    FROM
                        app_follows
                    WHERE
                        type = 0
                    GROUP BY
                        followId
                ) b ON a.id = b.followId
                WHERE
                    a.id IN (
                        SELECT
                            followId
                        FROM
                            app_follows
                        WHERE
                            type = 0
                        AND userId = ${this.ctx.user.userId}
                    )
                ORDER BY
                    b.followCount DESC
            `;
            const list = await this.circleEntity.query(sql);
            const data = JSON.parse(JSON.stringify(list));
            data.forEach(item => { item.cover = item.cover.split(','), item.followCount = `${item.followCount}人关注` });
            if (data.length === 0) {
                return {
                    success: false,
                    message: '未加入圈子',
                    data: []
                }
            }
            return {
                success: true,
                message: '查询成功',
                data: data
            }
        } catch (error) {
            throw new CoolCommException('查询失败');
        }
    }

    /**
     * 加入圈子
     * @param id 圈子id
     */
    async joinCircle(id: number) {
        try {
            const isJoin = await this.followsEntity.findOneBy({ type: 0, userId: this.ctx.user.userId, followId: id });
            if (isJoin) {
                return {
                    success: false,
                    message: '你已加入',
                    data: null
                };
            }
            await this.followsEntity.save({ type: 0, userId: this.ctx.user.userId, followId: id });
            return {
                success: true,
                message: '加入成功',
                data: null
            };
        } catch (error) {
            throw new CoolCommException('加入失败');
        }
    }

    /**
     * 退出圈子
     * @param id 圈子id
     */
    async exitCircle(id: number) {
        try {
            const result = await this.followsEntity.delete({ type: 0, userId: this.ctx.user.userId, followId: id });
            if (result) {
                return {
                    success: true,
                    message: '退出成功',
                    data: result
                };
            }
            return {
                success: false,
                message: '退出失败',
                data: null
            };
        } catch (error) {
            throw new CoolCommException('退出失败');
        }
    }

    /**
     * 圈子列表
     */
    async getCircleList() {
        // 查询状态为启用的圈子
        const list = await this.circleEntity.find({
            where: {
                status: 1
            },
        });
        const data = JSON.parse(JSON.stringify(list));
        data.forEach(item => {
            item.cover = item.cover.split(',');
            item.followCount = `${item.followCount}人关注`;
            item.postCount = `${item.postCount}条内容`;
        });
        return {
            success: true,
            message: '查询成功',
            data: data
        }
    }

    /**
     * 圈子详情
     * @param id 圈子id
     */
    async getCircleDetail(id: number) {
        try {
            const detail = await this.circleEntity.findOneBy({ id });
            const data = JSON.parse(JSON.stringify(detail));
            data.categoryIds = data.categoryIds.split(',').map(item => { return Number(item) });
            data.tags = await this.dictInfoService.values(data.categoryIds);
            data.cover = data.cover.split(',');
            if (this.ctx.user) {
                const isJoin = await this.followsEntity.findOneBy({ type: 0, userId: this.ctx.user.userId, followId: id });
                data.isJoin = isJoin ? true : false;
                data.isAuthor = data.openid === this.ctx.user.openid || this.ctx.user.openid === 'oabDj4oo1wQlQXlYmcz2ncvdfw0U' ? true : false;
            } else {
                data.isJoin = false;
                data.isAuthor = false;
            }
            return {
                success: true,
                message: '查询成功',
                data: data
            }
        } catch (error) {
            throw new CoolCommException('查询失败');
        }
    }


    /**
     * 创建圈子
     * @param name 圈子名称
     * @param description 圈子描述
     * @param images 圈子封面
     * @param categoryIds 圈子分类
     */
    async createCircle(name, description, images, categoryIds) {
        try {
            const openid = this.ctx.user.openid;
            const cover = images.join(',');
            categoryIds = categoryIds.join(',');
            const create = await this.circleEntity.save({ name, description, cover, categoryIds, openid });
            if (create) {
                return {
                    success: true,
                    message: '创建成功，等待审核',
                    data: create
                };
            }
            return {
                success: false,
                message: '创建失败',
                data: null
            };
        } catch (error) {
            throw new CoolCommException('创建失败');
        }
    }
}
